package com.phicomm.cloud.util;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.*;

public class ImageConvert {
    static BASE64Encoder encoder = new BASE64Encoder();
    static BASE64Decoder decoder = new BASE64Decoder();

    /**
     * @Description: 根据图片地址转换为字节数组字符串，并进行base64编码
     * @Author:
     * @CreateTime:
     * @return
     */
    public String getImageStr(String imgFile) {
        byte[] data = null;
        // 读取图片字节数组
        try {
            InputStream inputStream = new FileInputStream(imgFile);
            data = new byte[inputStream.available()];
            inputStream.read(data);
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 对字节数组Base64编码
        return encoder.encode(data);
    }

    /**
     * @Description: 将字节数组字符串进行Base64解码，并转换为图片
     * @Author:
     * @CreateTime:
     * @param imgStr base64编码字符串
     * @param path 图片路径-具体到文件
     * @return
     */
    public boolean generateImage(String imgStr, String path) {
        if (imgStr == null) return false;
        try {
            // Base64解码
            byte[] b = decoder.decodeBuffer(imgStr);
            // 调整异常数据
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            OutputStream out = new FileOutputStream(path);
            out.write(b);
            out.flush();
            out.close();
            return true;
        } catch (Exception e) {
            return false;
        }
    }

}
